package com.hejie.commentservice.repository;

import com.hejie.commentservice.entity.Comment;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface CommentRepository extends JpaRepository<Comment, Long> {
    // 根据视频ID查询评论，按创建时间倒序
    Page<Comment> findByVideoIdAndParentIdIsNullOrderByCreateTimeDesc(Long videoId, Pageable pageable);

    // 根据父评论ID查询回复，按创建时间正序
    Page<Comment> findByParentIdOrderByCreateTimeAsc(Long parentId, Pageable pageable);

    // 根据用户ID查询评论
    Page<Comment> findByUserIdOrderByCreateTimeDesc(Long userId, Pageable pageable);

    // 统计视频评论总数
    @Query("SELECT COUNT(c) FROM Comment c WHERE c.videoId = :videoId AND c.parentId IS NULL AND c.status = 1")
    Long countByVideoId(@Param("videoId") Long videoId);

    // 批量查询评论
    List<Comment> findByIdIn(List<Long> ids);

    // 根据视频ID删除所有评论（逻辑删除）
    @Modifying
    @Query("UPDATE Comment c SET c.status = 0 WHERE c.videoId = :videoId")
    void updateStatusByVideoId(@Param("videoId") Long videoId);

    // 点赞数+1
    @Modifying
    @Query("UPDATE Comment c SET c.likeCount = c.likeCount + 1 WHERE c.id = :id")
    void incrementLikeCount(@Param("id") Long id);

    // 点赞数-1
    @Modifying
    @Query("UPDATE Comment c SET c.likeCount = c.likeCount - 1 WHERE c.id = :id AND c.likeCount > 0")
    void decrementLikeCount(@Param("id") Long id);

    // 回复数+1
    @Modifying
    @Query("UPDATE Comment c SET c.replyCount = c.replyCount + 1 WHERE c.id = :parentId")
    void incrementReplyCount(@Param("parentId") Long parentId);

    // 回复数-1
    @Modifying
    @Query("UPDATE Comment c SET c.replyCount = c.replyCount - 1 WHERE c.id = :parentId AND c.replyCount > 0")
    void decrementReplyCount(@Param("parentId") Long parentId);
}